import { Router } from "express"
import { IcallbackFn, Ioracle } from "../../types"
// import { mail } from "../../hooks"
import { sendMail } from "./mail"
import multer from "multer"
import path from "path"
import { logger } from "../../utils"
import fs from "fs"
const upload = multer({ dest: "../uploadFile/asset" })

import { ERROR_RESULT, SUCCESS_RESULT } from "../../utils"


export default (router: Router, oracle: Ioracle, callbackFn: IcallbackFn) => {
  //抓取盘差资料
  router.post("/getAbnormalList", (req, res) => {
    const { account } = req.body

    let sql = " select rownum seq,a.header_id,a.action_dept "
    sql += " ,b.chinese_name,c.check_type "
    sql += " ,to_char(c.updated_date,'yyyymmdd hh24:mi:ss') updated_date "
    sql +=
      " from xx_general_asset_check_flow a,user_info_n b,xx_general_asset_check_header c "
    sql += " where a.action_klm = b.account "
    sql += " and c.status = '初盤完成' "
    sql += " and a.header_id = c.header_id "
    sql += " and c.flow_phase in ('盤差開單','報告開單') "
    sql += " and dept_code in (select distinct b.asset_dept "
    sql += " from user_info_n a,xx_assetmove_deptgroup b "
    sql += " where a.attribute1 = b.group_dept "
    sql += " and a.account = '" + account + "' "
    sql += " and a.job_status = 'employed' ) "
    //sql += " and a.flow_phase = '盤差開單' "
    //sql += " and a.action_klm = '" + account + "' "
    sql += " and a.sign_flag is null "

    callbackFn(res, oracle.connChaos, { sql })
  })

  //细项
  router.post("/getAbnormalDetail", (req, res) => {
    const { headerId } = req.body
    let sql = " select rownum seq,b.asset_no,b.asset_name,b.asset_qty,b.upload_file "
    sql += " from xx_general_asset_check_header a,xx_general_asset_check_line b "
    sql += " where a.header_id = b.header_id "
    sql += " and b.check_result is null "
    sql += " and a.header_id = '" + headerId + "' "

    callbackFn(res, oracle.connChaos, { sql })
  })

  //提交
  router.post("/sendList", (req, res) => {
    const { headerId, account,params } = req.body
    
    let sql = ""

    sql = " update xx_general_asset_check_line "
    sql += " set lose_reason = :loseReason "
    sql += " ,lose_action = :loseAction "
    sql += " where header_id = '" + headerId + "' "
    sql += " and asset_no = :assetNo "
    oracle
      .connChaos({ sql, isMulti: true, params:JSON.parse(params) })
      .then(() => {
        sql =
          " begin xx_general_asset_pkg.xx_general_asset_main('" +
          headerId +
          "','Y','','" +
          account +
          "');end; "
        oracle
          .connChaos({ sql })
          .then(() => {
            //发送邮件
            sql =
              " select case when substr(b.account,1,1) = 'x' then substr(b.account,9)||'@compeq.huizhou.gd.cn' "
            sql +=
              " when substr(b.account,1,1) = 'p' then substr(b.account,9)||'@compeq.com.tw' "
            sql +=
              " when substr(b.account,1,1) = 'q' then substr(b.account,9)||'@compeq-cq.com.cn' "
            sql +=
              " when substr(b.account,1,1) = 's' then substr(b.account,9)||'@compeq-sz.com.cn' "
            sql += " end as email,b.chinese_name "
            sql += " from xx_general_asset_check_flow a,user_info_n b "
            sql += " where a.header_id = '" + headerId + "' "
            sql += " and a.action_klm = b.account "
            sql += " and a.sign_flag is null "
            sql += " and b.job_status = 'employed' "
            oracle.connChaos({ sql }).then((result) => {
              if (result.data.length) {
                const { email, chinese_name } = result.data[0]
                const href =
                  "http://home70.compeq.huizhou.gd.cn/AppOracletest/general_asset/assetManage/asset_approve_report.html?dataType=approve&headerId=" +
                  headerId
                sendMail({
                  mailTo: email as string,
                  mailSubject: "固定資產系統-簽核通知郵件",
                  mailHtml: "./mail/generalAsset/abnormalList.ejs",
                  mailData: { chinese_name, href, headerId },
                })
                  .then(() => res.send(SUCCESS_RESULT))
                  .catch((err) => {
                    res.send({ code: 0, message: err })
                  })
              }
            })
          })
          .catch(() => {
            res.send(ERROR_RESULT)
          })
      })
      .catch((err) => {
        res.send({ code: 0, message: err })
      })
  })

  //上传附件
  router.post("/uploadFile", upload.single("file"), (req, res) => {
    const { headerId, assetNo } = req.body
    if (req.file?.originalname) {
      const filePath = req.file.path
      const fileExt = path.parse(req.file?.originalname).ext
      const fileName = req.file.filename + fileExt
      const oldName = filePath
      const newName = filePath + fileExt
      //原生的不带后缀名，替换文件名字，加上后缀名
      fs.renameSync(oldName, newName)
      let sql = " update xx_general_asset_check_line "
      sql += " set upload_file = '" + fileName + "' "
      sql += " where header_id = '" + headerId + "' "
      sql += " and asset_no = '" + assetNo + "' "
      oracle
        .connChaos({ sql })
        .then(() => {
          logger.info("附件上传OK!")
          res.send({ code: 200, message: "success", data: fileName })
        })
        .catch((err) => {
          logger.error("附件上传失败!" + err)
          res.send({ code: 0, message: err })
        })
    } else {
      logger.error("附件上传失败!")
      res.send(ERROR_RESULT)
    }

    // upload(req, res, function (err) {
    //   if (err instanceof multer.MulterError) {
    //     logger.error("附件上传错误!" + err)
    //     res.send(ERROR_RESULT)
    //   } else if (err) {
    //     // 发生错误
    //     logger.error("附件上传错误!" + err)
    //     res.send(ERROR_RESULT)
    //   }
    //   if (req.file?.originalname) {
    //     const fileExt = path.parse(req.file?.originalname).ext
    //     const filename = req.file.filename + fileExt
    //     let sql = " update xx_general_asset_check_line "
    //     sql += " set upload_file = '" + filename + "' "
    //     sql += " where header_id = '" + headerId + "' "
    //     oracle
    //       .connChaos({ sql })
    //       .then(() => {
    //         logger.info("附件上传OK!")
    //         res.send(SUCCESS_RESULT)
    //       })
    //       .catch((err) => {
    //         res.send({ code: 0, message: err })
    //       })
    //   } else {
    //     logger.error("未找到附件!")
    //     res.send(ERROR_RESULT)
    //   }
    //   // 一切都好
    // })
  })

  //下载附件
  router.post('/download', (req, res) => {
    const {fileName} = req.body
    const filePath = '../uploadFile/asset/' + fileName
    const f = fs.createReadStream(filePath);
    res.writeHead(200, {
      //'Content-Type': 'application/force-download',
      'Content-Type': 'application/octet-stream',
      'Content-Disposition': 'attachment; filename=' + fileName,
      'Access-Control-Expose-Headers': 'Content-Disposition',//核心配置
    });
    f.pipe(res);
    //res.download(filePath)
  })

  return router
}
